<template>
	<view class="app">
		<view class="main">
			<image class="bgImg" src="../../static/bg.png"></image>
			<view class="searchView" v-if="showCtrlView==false">
				<image class="top_window" :src="topImage" mode="widthFix"></image>
				<label class="des">
					<text>{{$t('index.hw.hinsOne')}}
						{{$t('index.hw.hinsTwo')}}</text>
				</label>
				<view class="searchBtn" @click="searchAction()">
					<image class="searchBg" src="../../static/button_bg.png" mode="widthFix"></image>
					<label class="searchText">
						<text>{{$t('index.hw.search')}}</text>
					</label>
				</view>
			</view>
			<view class="content" v-if="showCtrlView">
				<!-- 产品图 -->
				<image v-if="a8TopImgIndex == 0 && blueToothName == 'fungeneA8'" class="ctrl_top_window" src="../../static/air_logo_top_0.png" mode="widthFix" fade-show="true"></image>
				<image v-if="a8TopImgIndex == 1 && blueToothName == 'fungeneA8'" class="ctrl_top_window" src="../../static/air_logo_top_1.png" mode="widthFix" fade-show="true"></image>
				<image v-if="a8TopImgIndex == 2 && blueToothName == 'fungeneA8'" class="ctrl_top_window" src="../../static/air_logo_top_2.png" mode="widthFix" fade-show="true"></image>
				<image v-if="a8TopImgIndex == 3 && blueToothName == 'fungeneA8'" class="ctrl_top_window" src="../../static/air_logo_top_3.png" mode="widthFix" fade-show="true"></image>
				<image v-if="a8TopImgIndex == 4 && blueToothName == 'fungeneA8'" class="ctrl_top_window" src="../../static/air_logo_top_4.png" mode="widthFix" fade-show="true"></image>
				
				<image v-if="s5TopImgIndex == 0 && blueToothName == 'fungeneS5'" class="ctrl_top_window" src="../../static/S5_index_0.png" mode="widthFix" fade-show="true"></image>
				<image v-if="s5TopImgIndex == 1 && blueToothName == 'fungeneS5'" class="ctrl_top_window" src="../../static/S5_index_1.png" mode="widthFix" fade-show="true"></image>
				<image v-if="s5TopImgIndex == 2 && blueToothName == 'fungeneS5'" class="ctrl_top_window" src="../../static/S5_index_2.png" mode="widthFix" fade-show="true"></image>
				<image v-if="s5TopImgIndex == 3 && blueToothName == 'fungeneS5'" class="ctrl_top_window" src="../../static/S5_index_3.png" mode="widthFix" fade-show="true"></image>
				
				<view class="stateView">
					<image class="better" v-show="better>80&&better<=100" src="../../static/better_0.png"></image>
					<image class="better" v-show="better>60&&better<=80" src="../../static/better_1.png"></image>
					<image class="better" v-show="better>40&&better<=60" src="../../static/better_2.png"></image>
					<image class="better" v-show="better>20&&better<=40" src="../../static/better_3.png"></image>
					<image class="better" v-show="better<=20" src="../../static/better_4.png"></image>
					<text class="betterDes" v-show="better<=100">{{''+better+'%'+''}}</text>

					<!--  其他 -->
					<image class="water" v-show="water>80&&water<=100&&blueToothName!='fungeneS5'"
						src="https://fungene.cc/fungene_app_static/src/ic_top.png"></image>
					<image class="water" v-show="water>60&&water<=80&&blueToothName!='fungeneS5'"
						src="https://fungene.cc/fungene_app_static/src/ic_hight.png"></image>
					<image class="water" v-show="water>40&&water<=60&&blueToothName!='fungeneS5'"
						src="https://fungene.cc/fungene_app_static/src/ic_middle.png"></image>
					<image class="water" v-show="water<=20&&blueToothName!='fungeneS5'"
						src="https://fungene.cc/fungene_app_static/src/ic_low.png"></image>

					<!-- S5 -->
					<image class="water" v-show="water>20&&water<=100&&blueToothName=='fungeneS5'"
						src="https://fungene.cc/fungene_app_static/src/ic_top.png"></image>
					<image class="water" v-show="water>0&&water<=20&&blueToothName=='fungeneS5'"
						src="https://fungene.cc/fungene_app_static/src/ic_middle.png"></image>
					<image class="water" v-show="water==0&&blueToothName=='fungeneS5'"
						src="https://fungene.cc/fungene_app_static/src/ic_low.png"></image>

					<text class="betterDes"
						v-show="water<=100 && blueToothName != 'fungeneS5'">{{''+water+'%'+''}}</text>

				</view>

				<view>
					<view class="section">
						<text class="sectionTitle">{{$t('air.smart')}}</text>
						<view class="modalView">
							<view class="row_left" :style="{'background':modal===0?'#735B49':'rgba(255,255,255,0.5)'}"
								@click="setModal(0)"><text
									:style="{'color':modal===0?'#FFF':'#998071'}">{{$t('air.auto')}}</text>
							</view>
							<view class="row_right" :style="{'background':modal===1?'#735B49':'rgba(255,255,255,0.5)'}"
								@click="setModal(1)"><text
									:style="{'color':modal===1?'#FFF':'#998071'}">{{$t('air.fast')}}</text>
							</view>
						</view>
					</view>
					
					<view class="section" v-show="!hideFan">
						<text class="sectionTitle">{{$t('air.fan')}}</text>
						<view class="sliderView">
							<view class="dangDiv">
								<view class="dang">{{ fanLevel > 0 ? fanLevel + $t('air.gear') : $t('air.close')}}
								</view>
							</view>
							<slider activeColor="#735B49" backgroundColor="#FAF7FF" blockColor="#E9D8CD" blockSize="28"
								@changing="changingDang" @change="changeDang" max="10" min="0" step="1"
								style="margin:15px 8% auto 8%;" :value="fanLevel"></slider>
						</view>
					</view>
					
<!-- 					<view class="section">
						<text class="sectionTitle">{{$t('air.concentration')}}</text>
						<view class="sliderView">
							<view class="dangDiv">
								<view class="dang">{{ nd + '%' }}</view>
							</view>
							<slider activeColor="#735B49" backgroundColor="#FAF7FF" blockColor="#E9D8CD" blockSize="28"
								@changing="changingND" @change="changeND" max="100" min="1" step="1"
								style="margin:15px 8% auto 8%;" :value="nd"></slider>
						</view>
					</view> -->
					
					<!-- 工作时间 -->
					<view>
						<view style="margin-left: 5px;margin-bottom: 10px;">
							<uni-section :title="workTimeDes" titleColor="#92735c" titleFontSize="12px" v-slot:right>
								<view style="width: 200px;height: 100%;text-align: right;">
									<picker style="flex: 1;" :value="workTimeIndex" :range="workTimeArray" @change="workTimeChange">
										 <view class="desText">{{workTimeArray[workTimeIndex] + 's'}}</view>
									</picker>
								</view>
							</uni-section>
						</view>
					</view>
					
					<!-- 间歇时间 -->
					<view >
						<view style="margin-left: 5px;margin-bottom: 10px;">
							<uni-section :title="sleepTimeDes" titleColor="#92735c" titleFontSize="12px" v-slot:right>
								<view style="width: 200px;height: 100%;text-align: right;">
									<picker style="flex: 1;" :value="sleepTimeIndex" :range="sleepTimeArray" @change="sleepTimeChange">
										 <view class="desText">{{sleepTimeArray[sleepTimeIndex] + 's'}} </view>
									</picker>
								</view>
							</uni-section>
						</view>
					</view>
					
					<view class="section" v-show="blueToothName != 'fungeneS5'">
						<text class="sectionTitle">{{$t('air.save')}}</text>
						<view class="modalView">
							<view class="row_left"
								:style="{'background':conservation===1 || conservation === 3?'#735B49':'rgba(255,255,255,0.5)'}"
								@click="setConservation(1)"><text
									:style="{'color':conservation===1 || conservation === 3?'#FFF':'#998071'}">{{$t('air.sleep')}}</text>
							</view>
							<view class="row_right"
								:style="{'background':conservation===2 || conservation === 3?'#735B49':'rgba(255,255,255,0.5)'}"
								@click="setConservation(2)"><text
									:style="{'color':conservation===2 || conservation === 3?'#FFF':'#998071'}">{{$t('air.leave')}}</text>
							</view>
						</view>
					</view>
					
					<view v-show="conservation===1 || conservation === 3">
						<view style="margin-left: 5px;margin-bottom: 10px;">
							<uni-section :title="sleepStartDes" titleColor="#92735c" titleFontSize="12px" v-slot:right>
								<view style="width: 200px;height: 100%;text-align: right;">
									<picker style="flex: 1;" mode="time" :value="sleepStartTime" @change="bindSleepStartTimeChange">
										 <view class="desText">{{sleepStartTime}}</view>
									</picker>
								</view>
							</uni-section>
						</view>
					</view>
					
					<view v-show="conservation===1 || conservation === 3">
						<view style="margin-left: 5px;margin-bottom: 10px;">
							<uni-section :title="sleepEndDes" titleColor="#92735c" titleFontSize="12px" v-slot:right>
								<view style="width: 200px;height: 100%;text-align: right;">
									<picker mode="time" :value="sleepEndTime"  @change="bindSleepEndTimeChange">
										<view class="desText">{{sleepEndTime}}</view>
									</picker>
								</view>
							</uni-section>
						</view>
					</view>

					<view class="section" v-show="!hideLight">
						<text class="sectionTitle">{{$t('air.light')}}</text>
						<view class="modalView">
							<view class="row_one" :style="{'background':light===2?'#735B49':'rgba(255,255,255,0.5)'}"
								@click="setLight(2)"><text
									:style="{'color':light===2?'#FFF':'#998071'}">{{$t('air.alway')}}</text>
							</view>
							<view class="row_two" :style="{'background':light===1?'#735B49':'rgba(255,255,255,0.5)'}"
								@click="setLight(1)"><text
									:style="{'color':light===1?'#FFF':'#998071'}">{{$t('air.whenOut')}}</text>
							</view>
							<view class="row_three" :style="{'background':light===0?'#735B49':'rgba(255,255,255,0.5)'}"
								@click="setLight(0)"><text
									:style="{'color':light===0?'#FFF':'#998071'}">{{$t('air.close')}}</text>
							</view>
						</view>
					</view>

					<view class="section" v-show="!hideLight">
						<view class="colorTitleDiv">
							<text class="sectionTitle">{{$t('air.lightColor')}}</text>
							<view class="colorBlock" :style="{'background':color}"></view>
						</view>

						<view class="colorPanel">
							<zebraColorPicker v-model="color" @input="changeColor" @sendColor="sendColor">
							</zebraColorPicker>
						</view>
					</view>

					<view>
						<view style="margin-left: 5px;margin-bottom: 10px; ">
							<uni-section :title="clean" titleColor="#92735c" titleFontSize="12px" v-slot:right>
								<switch :checked="cleanDevice" color="#BE9F88" @change="cleanChange" slot="right">
								</switch>
							</uni-section>
						</view>
					</view>

					<view>
						<view style="margin-left: 5px;margin-bottom: 10px; ">
							<uni-section :title="deviceOnlyIdName" titleColor="#92735c" titleFontSize="12px"
								v-slot:right @click="copyDeviceId()">
								<view style="display: flex;flex-direction: row;align-items: center;"
									@click="copyDeviceId()">
									<text style="margin-right: 10px;color: #92735c;"
										@click="copyDeviceId()">{{deviceOnlyId}}</text>
									<button style="color: #92735c;background-color: rgba(255, 255, 255, 0.5);"
										type="default" size="mini" @click="copyDeviceId()">{{$t('air.copy')}}</button>
								</view>
							</uni-section>
						</view>
					</view>

				</view>
			</view>

			<view class="hud" v-if="open == false && showCtrlView"></view>
		</view>
		<view class="footer" v-if="showCtrlView == true">
			<image style="width: 100%;position: absolute;" src="../../static/bottom_bg.png" mode="widthFix"></image>
			<image class="on" @click="setOn(false)" src='../../static/ic_on.png' mode="widthFix" v-if="open == true">
			</image>
			<image class="on" @click="setOn(true)" src='../../static/ic_off.png' mode="widthFix" v-if="open == false">
			</image>
		</view>

		<view>
			<!--l蓝牙列表弹窗-->
			<uni-popup ref="popup">
				<uni-card is-shadow=true padding="0" spacing="0">
					<view class="dialogTitle">{{$t('index.deviceList')}}</view>
					<scroll-view scroll-y=true>
						<view class="popup-content" style="color: black;width: 70vw;">
							<uni-list>
								<view v-for="(device,index) in bluetoothList" :key="index">
									<uni-list-item :title=" deviceName +  device.name" :note="'id：' + device.deviceId"
										link @click="clickListItem(index)">
										<template v-slot:footer>
											<view v-show="device.isChoose == true" style="margin-top: 22px;">
												<uni-icons type="checkmarkempty" size="30"></uni-icons>
											</view>
										</template>
									</uni-list-item>
								</view>
							</uni-list>
						</view>
					</scroll-view>
				</uni-card>
			</uni-popup>
		</view>

	</view>
</template>

<script src="">
	import zebraColorPicker from "../../conpons/components/zebra-color-picker-sketch/zebra-color-picker-sketch.vue"

	function ab2hex(buffer) {
		const hexArr = Array.prototype.map.call(
			new Uint8Array(buffer),
			function(bit) {
				return ('00' + bit.toString(16)).slice(-2)
			}
		)
		return hexArr.join('')
	}
	export default {
		components: {
			zebraColorPicker
		},
		data() {
			return {
				clean: "清洁模式",
				deviceName: '设备蓝牙名称：',
				deviceOnlyIdName: '设备id：',
				blueToothName: 'fungeneA8',
				topImage: '../../static/air_logo_top_0.png',
				a8TopImgIndex: 0,
				s5TopImgIndex: 0,
				loading: false,
				loadingText: "搜索",
				deviceId: "",
				hideFan: false,
				hideLight: false,
				//蓝牙列表
				bluetoothList: [],
				//蓝牙三件套
				uuid: "",
				characteristics: "", // 写入用的特征值
				noticeCharacteristics: "", // 监听用的特征值
				showCtrlView: false,

				better: 110, //电量蓝牙
				water: 110, //液量蓝牙

				open: true, //开关蓝牙   01 00       
				fanLevel: 1, //风扇蓝牙   02 09
				modal: 0, //模式蓝牙   03 01  ->    00 自动   01 速香
				nd: 0, //浓度蓝牙   04 100
				conservation: 0, //场景蓝牙   05 01        00 关闭   01  睡眠模式    02   离家模式   03  全选
				light: 0, //氛围灯蓝牙  06 02      00 关闭   01  出雾时常亮   02 常亮
				color: '#ffffff', //氛围灯颜色  07 faf1f2 
				cleanDevice: false,
				deviceOnlyId: '', //设备唯一id
				
				workTime:0, //工作时间
				sleepTime:0,//间歇时间
				workTimeIndex: 0,
				sleepTimeIndex: 0,
				workTimeArray: [],
				sleepTimeArray: [],
				workTimeDes: "工作时间",
				sleepTimeDes: "间歇时间",
				
				
				sleepStartTime: "00:00",
				sleepEndTime: "00:00",
				sleepStartDes: "睡眠模式开始时间",
				sleepEndDes: "睡眠模式结束时间"
			}
		},


		onLoad(option) {
			this.clean = this.$t('index.clean')
			this.deviceName = this.$t('index.deviceName')
			this.deviceOnlyIdName = this.$t('air.deviceOnlyIdName')
			this.sleepStartDes = this.$t('air.sleepStart')
			this.sleepEndDes = this.$t('air.sleepEnd')
			this.workTimeDes = this.$t('air.workTime')
			this.sleepTimeDes = this.$t('air.sleepTime')
			
			
			var startArray = []
			var endArray = []
			for (var i = 1; i < 200; i++) {
				startArray.push(i.toString())
			}
			
			for (var i = 30; i < 300; i++) {
				endArray.push(i.toString())
			}
			this.workTimeArray = startArray
			this.sleepTimeArray = endArray

			if (option.device == "S5") {
				this.hideFan = true;
				this.hideLight = true;
				this.topImage = '../../static/S5_index_0.png'
				this.blueToothName = 'fungeneS5'
			} else if (option.device == "FUN") {
				this.topImage = '../../static/fun_logo_top.png'
				this.blueToothName = 'fungeneFUN'
			}
			const disconnect = this.$t('index.disconnect')
			var that = this;
			uni.onBLEConnectionStateChange(function(res) {
				if (res.connected == false) {
					uni.showToast({
						title: disconnect,
						icon: "none",
						duration: 2e3
					});
					that.deviceId = "";
					that.uuid = "";
					that.characteristics = "";
					that.showCtrlView = false;
				}
			});
		},
		onLaunch: function() {},
		onShow: function() {
			// uni.openBluetoothAdapter({
			// 	success: function(res) { // 开启蓝牙成功
			// 		console.log('已经开启蓝牙权限')
			// 	},
			// 	fail: function(msg) {
			// 		console.log(msg.errMsg)
			// 		uni.showModal({
			// 			content: '蓝牙没打开或者没授权蓝牙权限',
			// 			showCancel: false,
			// 			confirmText: '好的',
			// 			confirmColor: '#3e90fa',
			// 			success: res => {
			// 				if (res.confirm) {}
			// 			}
			// 		})
			// 	}
			// })
		},
		beforeDestroy() {
			uni.closeBluetoothAdapter({
				success(res) {
					console.log(res)
				}
			})
		},

		methods: {
			clickListItem(index) {
				const connecting = this.$t('index.connecting')
				let item = this.bluetoothList[index]
				item.isChoose = true;
				let that = this;
				setTimeout(function() {
					that.deviceId = item.deviceId;
					that.connetBleBluetooth();
					that.$refs.popup.close();
					uni.showLoading({
						title: connecting
					});
				}, 500);
			},
			
			workTimeChange: function(e) {
				const index = e.detail.value
				const value = this.workTimeArray[index]
				
			    this.workTimeIndex = index
				
				var valueString = "0"
				if (value > 99){
					valueString = "0" + value
				}else if(value > 10 && value < 100) {
					valueString = "00" + value
				}else{
					valueString = "000" + value
				}
				console.log("工作时间===" + valueString);
				
				this.writeInfoToBluetooth("09", valueString);
			},
			sleepTimeChange: function(e) {
				const index = e.detail.value
				const value = this.sleepTimeArray[index]
			    this.sleepTimeIndex = index
				
				var valueString = "0"
				if (value > 99){
					valueString = "0" + value
				}else if(value > 10 && value < 100) {
					valueString = "00" + value
				}else{
					valueString = "000" + value
				}
				console.log("间歇时间===" + valueString);
				this.writeInfoToBluetooth("10", valueString);
			},
			
			bindSleepStartTimeChange: function(e) {
				let startTime = e.detail.value
			    this.sleepStartTime = startTime
				const startTimeValue = startTime.replace(":", "");
				this.writeInfoToBluetooth("11", startTimeValue);
				
			},
			bindSleepEndTimeChange: function(e) {
				let endTime = e.detail.value
			    this.sleepEndTime = endTime
				const endTimeValue = endTime.replace(":", "");
				this.writeInfoToBluetooth("12", endTimeValue);
			},
			showBLEListDialog() {
				if (this.showCtrlView == false) {
					this.$refs.popup.open('center')
				}
			},
			setOn(r) {
				this.open = r
				this.writeInfoToBluetooth("01", "0" + (r == false ? "0" : "1"));
			},
			changeColor(value) {
				this.color = value.hex
			},
			sendColor() {
				console.log(this.color);
				let col = this.color.replace("#", "");
				this.writeInfoToBluetooth("07", col);
			},
			setLight(l) {
				this.light = l
				this.writeInfoToBluetooth("06", "0" + l);
			},
			setModal(m) {
				this.modal = m
				this.writeInfoToBluetooth("03", "0" + m);
			},
			setConservation(c) {
				switch (c) {
					case 1:
						if (this.conservation === 2) {
							this.conservation = 3
						} else if (this.conservation === 1) {
							this.conservation = 0
						} else if (this.conservation === 3) {
							this.conservation = 2
						} else if (this.conservation === 0) {
							this.conservation = 1
						}
						break;
					case 2:
						if (this.conservation === 2) {
							this.conservation = 0
						} else if (this.conservation === 1) {
							this.conservation = 3
						} else if (this.conservation === 3) {
							this.conservation = 1
						} else if (this.conservation === 0) {
							this.conservation = 2
						}
						break;
					default:
						this.conservation = 0
						break;
				}
				this.writeInfoToBluetooth("05", "0" + this.conservation);
			},
			cleanChange(e) {
				const content = this.$t('index.cleanHins')
				const cancel = this.$t('cancel')
				const sure = this.$t('sure')
				var that = this;
				if (e.detail.value) {
					uni.showModal({
						content: content,
						cancelText: cancel,
						confirmText: sure,
						confirmColor: "#3e90fa",
						success: function success(res) {
							if (res.confirm) {
								that.cleanDevice = e.detail.value;
								that.writeInfoToBluetooth("08", e.detail.value == true ? "01" : "00");
							}
							if (res.cancel) {
								that.cleanDevice = false;
							}
						}
					});
				} else {
					this.cleanDevice = e.detail.value;
					this.writeInfoToBluetooth("08", e.detail.value == true ? "01" : "00");
				}
			},
			changeDang(e) {
				this.fanLevel = e.detail.value;
				this.writeInfoToBluetooth("02", e.detail.value == 10 ? "10" : "0" + e.detail.value);
			},
			changingDang(e) {
				this.fanLevel = e.detail.value;
			},
			changeND(e) {
				this.nd = e.detail.value;
				let newNd = "01"
				if (this.nd < 10) {
					newNd = "000" + this.nd
				} else if (this.nd >= 10 && this.nd <= 99) {
					newNd = "00" + this.nd
				} else {
					newNd = "0100"
				}
				this.writeInfoToBluetooth("04", newNd);
			},
			changingND(e) {
				this.nd = e.detail.value;
			},
			copyDeviceId() { // 复制设备id
				const succ = this.$t('air.copySucc')

				let that = this;
				uni.setClipboardData({
					data: that.deviceOnlyId,
					success: function() {
						uni.showToast({
							title: succ,
							icon: 'success',
						});
					}
				})

			},
			searchAction() {
				if (this.loading) {
					this.stopSearchAction();
				} else {
					let that = this
					const mess = this.$t('index.hins')
					const ok = this.$t('index.ok')

					uni.openBluetoothAdapter({
						success: function(res) { // 开启蓝牙成功
							console.log('已经开启蓝牙权限')
							that.seachAction();
						},
						fail: function(msg) {
							console.log(msg.errMsg)
							uni.showModal({
								content: mess,
								showCancel: false,
								confirmText: ok,
								confirmColor: '#3e90fa',
								success: res => {
									if (res.confirm) {

									}
								}
							})
						}
					})
				}
			},
			// 开始搜索
			seachAction() {
				const searching = this.$t('index.searching')
				this.loading = true;
				this.loadingText = searching;
				uni.showLoading({
					title: this.loadingText
				});
				this.bluetoothList = [];
				var that = this;
				uni.startBluetoothDevicesDiscovery({
					success: function success(res) {
						//services: ['0000FFF0', '0000ffe0'],
						// console.log("搜索到设备---", res);
						uni.onBluetoothDeviceFound(function(el) {
							el.devices.forEach(function(item, index) {
								if (item.name.includes(that.blueToothName)) {
									that.$set(item, "isChoose", false);
									console.log("搜索到设备---", item);
									uni.hideLoading();
									that.bluetoothList.push(item);
									that.showBLEListDialog();
								}
							});
						});
					}
				});
			},
			// 关闭搜索
			stopSearchAction() {
				this.loading = false;
				this.loadingText = "搜索";
				uni.stopBluetoothDevicesDiscovery({
					success: function success(res) {
						console.log("停止搜索---", res);
					},
					fail: function fail(res) {
						console.log("停止搜索失败---", res);
					}
				});
			},
			// 连接Ble蓝牙 
			connetBleBluetooth() {
				var that = this;
				var devId = this.deviceId;
				uni.createBLEConnection({
					deviceId: devId,
					success: function success(res) {
						//需延时连接，不然会报错
						setTimeout(function() {
							uni.getBLEDeviceServices({
								deviceId: that.deviceId,
								success: function success(res) {
									console.log("res.services===" + JSON.stringify(res
										.services));
									const isAndroidAPP = that.isAndroidApp();
									if (isAndroidAPP) {
										that.uuid = res.services[2].uuid;
									} else {
										that.uuid = res.services[0].uuid;
									}
									setTimeout(() => {
										that.getBluetoothInfo();
									}, 1000);
								}
							});
						}, 1000);
					},
					fail: function fail(res) {
						uni.hideLoading();
					}
				});
			},
			// 获取蓝牙信息
			getBluetoothInfo() {
				var that = this;
				this.setBleMaxMut();
				uni.getBLEDeviceCharacteristics({
					deviceId: this.deviceId,
					serviceId: this.uuid,
					success: function success(res) {
						console.log("res.characteristics===" + JSON.stringify(res.characteristics));
						// console.log("特征值characteristics1======" + res.characteristics[0].uuid);
						// console.log("特征值characteristics2======" + res.characteristics[1].uuid);
						// console.log("特征值characteristics3======" + res.characteristics[2].uuid);
						const isAndroidAPP = that.isAndroidApp();
						if (isAndroidAPP) {
							that.characteristics = res.characteristics[0].uuid;
							that.noticeCharacteristics = res.characteristics[0].uuid;
						} else {
							that.characteristics = res.characteristics[0].uuid;
							that.noticeCharacteristics = res.characteristics[1].uuid;
						}
						that.notifcation();
						that.stopSearchAction();
						//关闭搜索
						setTimeout(function() {
							that.writeInfoToBluetooth("77", "88");
						}, 200);
						setTimeout(function() {
							that.writeInfoToBluetooth("33", "44");
						}, 400);
						that.showCtrlView = true;
						uni.hideLoading();
					},
					fail: function fail(res) {
						console.log("获取特征值失败===" + res);
						uni.hideLoading();
					}
				});
			},
			setBleMaxMut() {
				let _this = this;
				uni.setBLEMTU({
					deviceId: _this.deviceId,
					mtu: 512,
					success(res) {
						console.log("设置最大值成功")
					}
				});
			},
			//订阅  监听
			notifcation() {
				var that = this;
				var deviceId = this.deviceId;
				var serviceId = this.uuid;
				var characteristicId = this.noticeCharacteristics;
				// console.log("deviceId=" + deviceId);
				// console.log("serviceId=" + serviceId);
				// console.log("characteristicId=" + characteristicId);
				setTimeout(() => {
					uni.notifyBLECharacteristicValueChange({
						state: true,
						// 启用 notify 功能
						// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
						deviceId: deviceId,
						// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
						serviceId: serviceId,
						// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
						characteristicId: characteristicId,
						success: function success(res) {
							console.log("订阅监听成功", res);
							that.onValueChange();
						},
						fail: function fail(res) {
							console.log("订阅监听失败", res.errMsg);
						}
					});
				}, 200);
			},
			// 监听数值变化
			onValueChange() {
				//             电量    液量   开关  风扇档位    模式   浓度    场景   氛围灯开关   氛围灯颜色   图片    自清洁模式
				//格式  6677    0088   0088    01    09        01   0099     01      02      ffffff      01        01
				var that = this;
				uni.onBLECharacteristicValueChange(function(res) {
					var result = ab2hex(res.value);
					// uni.showToast({
					// 	title: "收到傻逼新的蓝牙信息啦=" + result
					// })

					console.log('result=' + result);
					if (result.includes("3344")) {
						result = result.replace("3344", "");
						if (result.length == 0) {
							return
						}
						console.log('result=3344' + result);
						let deviceID = "";
						if (that.blueToothName == 'fungeneS5') {
							deviceID = "S5";
						} else if (that.blueToothName == 'fungeneA8') {
							deviceID = "A8";
						}
						var one = parseInt(result.substr(0, 4)).toString(16);
						var two = parseInt(result.substr(4, 4)).toString(16);
						var three = parseInt(result.substr(8, 4)).toString(16);
						var four = parseInt(result.substr(12, 4)).toString(16);
						var five = parseInt(result.substr(16, 4)).toString(16);
						var six = parseInt(result.substr(20, 4)).toString(16);

						if (one.length == 1) {
							one = '0' + one
						}
						if (two.length == 1) {
							two = '0' + two
						}
						if (three.length == 1) {
							three = '0' + three
						}
						if (four.length == 1) {
							four = '0' + four
						}
						if (five.length == 1) {
							five = '0' + five
						}
						if (six.length == 1) {
							six = '0' + six
						}
						deviceID += one + two + three + four + five + six
						
						that.deviceOnlyId = deviceID.toUpperCase();
					}
					if (result.includes("6677")) {
						result = result.replace("6677", "");
						if (result.length == 0) {
							return
						}
						console.log('result=6677' + result);
						//电量
						that.better = parseInt(result.substr(0, 4));
						//液量
						that.water = parseInt(result.substr(4, 4));
						//开关
						that.open = parseInt(result.substr(8, 2)) == 0 ? false : true;
						//风扇档位
						that.fanLevel = parseInt(result.substr(10, 2));
						//模式
						that.modal = parseInt(result.substr(12, 2));
						//浓度
						that.nd = parseInt(result.substr(14, 4));
						//场景
						that.conservation = parseInt(result.substr(18, 2)) > 3 ? 0 : parseInt(result
							.substr(18,
								2));
						//氛围灯开关
						that.light = parseInt(result.substr(20, 2));
						//氛围灯颜色
						let colorString = "#" + parseInt(result.substr(22, 4)).toString(16) + parseInt(
							result
							.substr(26, 4)).toString(16) + parseInt(result.substr(30, 4)).toString(16)
						that.color = colorString;

						//设备颜色图index
						let index = parseInt(result.substr(34, 2));
						if (that.blueToothName == 'fungeneS5' && index >= 0 && index < 6) {
							that.s5TopImgIndex = index;
						} else if (that.blueToothName == 'fungeneA8' && index >= 0 && index < 6) {
							that.a8TopImgIndex = index;
						}
						//清洁模式
						let clean = parseInt(result.substr(36, 2));
						that.cleanDevice = clean == 0 ? false : true;
						
						// 工作时间
						let workTime = parseInt(result.substr(38, 4));
						that.workTime = workTime
						
						for (var i = 0; i < that.workTimeArray.length; i++) {
							if(parseInt(that.workTimeArray[i]) == workTime){
								that.workTimeIndex = i
							}
						}
						
						//间歇时间
						let sleepTime = parseInt(result.substr(42, 4));
						that.sleepTime = sleepTime
						
						for (var i = 0; i < that.sleepTimeArray.length; i++) {
							if(parseInt(that.sleepTimeArray[i]) == sleepTime){
								that.sleepTimeIndex = i
							}
						}
						
						//睡眠开始时间
						let sleepStartTimeStr = result.substr(46, 4);
						let hour1 = sleepStartTimeStr.slice(0,2)
						let min1 = sleepStartTimeStr.slice(2,4)
						that.sleepStartTime = hour1 + ":" + min1
						
						//睡眠结束时间
						let sleepEndTimeStr = result.substr(50, 4);
						console.log('sleepEndTimeStr=' + sleepEndTimeStr);
						let hour2 = sleepEndTimeStr.slice(0,2)
						let min2 = sleepEndTimeStr.slice(2,4)
						that.sleepEndTime = hour2 + ":" + min2
						
					}
				});
			},
			// 写数据
			// type 看属性注释
			writeInfoToBluetooth(type, value) {
				if (this.deviceId == "") {
					const btHins = this.$t('btHins')
					uni.showToast({
						title: btHins,
						icon: "none",
						duration: 2e3
					});
					return;
				}
				var hex = "6677" + type + value;
				//要发送的信息
				var typedArray = new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function(h) {
					return parseInt(h, (type.includes("07") ? 16 : 10));
				}));
				console.log(typedArray);
				var buffer1 = typedArray.buffer;
				var devId = this.deviceId;
				var uuid = this.uuid;
				var chartId = this.characteristics;
				uni.writeBLECharacteristicValue({
					deviceId: devId,
					serviceId: uuid,
					characteristicId: chartId,
					value: buffer1,
					writeType: "writeNoResponse",
					success: function success(res) {
						console.log("蓝牙写入成功", res.errMsg);
					},
					fail: function fail(res) {
						uni.showToast({
							title: "error：" + res
						})
						console.log("写入失败--------", res);
					}
				});
			},
			isAndroidApp() {
				// #ifdef  APP-PLUS
				if (uni.getSystemInfoSync().platform === 'android') {
					return true
				} else {
					return false
				}
				// #endif
				return false;
			},
			onShareAppMessage() {},
			onShareTimeline() {}
		}
	}
</script>

<style lang="scss">
	.app {
		width: 100%
	}

	.content {
		display: flex;
		flex-direction: column
	}

	.logo {
		height: 200rem;
		margin-top: 200rem;
		width: 200rem
	}

	.serach {
		text-align: center
	}

	.serach {
		margin-top: 50px;
		width: 380px
	}

	.water {
		height: 21px;
		margin-left: 10px;
		margin-top: 3px;
		width: 16px
	}

	.sliderView {
		background-color: hsla(0, 0%, 100%, .5);
		border-radius: 10px;
		margin: 5px 15px auto;
		height: 100px
	}

	.dangDiv {
		display: flex;
		flex-direction: row
	}

	.rowBtn {
		width: 77%
	}

	.line {
		background-color: #b19581;
		height: .8px;
		margin-top: 5px;
		margin-left: 10px;
		margin-right: 10px;
		border-radius: 0.4px;
	}

	.sectionTitle {
		color: #92735c;
		font-size: 12px;
		margin-left: 15px
	}

	.better {
		height: 24px;
		width: 11px
	}

	.betterDes {
		font-size: 12px;
		margin-left: 7px;
		margin-top: 9px
	}

	.section {
		margin-bottom: 15px;
		margin-top: 15px
	}

	.ctrl_top_window {
		margin: 30px 25% 0% 25%;
		max-width: 50%;
		padding-top: 5px;
	}

	.searchView {
		align-items: center;
		display: flex;
		flex-direction: column;
		justify-content: center
	}

	.bgImg {
		height: 100%;
		left: 0;
		position: fixed;
		top: 0;
		width: 100%;
		z-index: -1
	}

	.top_window {
		margin: 30px 5% auto;
		max-width: 90%
	}

	.des {
		font-size: 14px;
		margin-top: 15px;
		text-align: center
	}

	.searchBtn {
		align-items: center;
		border-radius: 24px;
		justify-content: center;
		margin-bottom: 50px;
		margin-top: 55px;
	}

	.searchBg {
		display: flex;
		height: 48px;
		width: 188px
	}

	.searchText {
		position: absolute;
		height: 48px;
		width: 188px;
		text-align: center;
		margin-top: -40px;
	}

	.stateView {
		display: flex;
		flex-direction: row;
		height: 25px;
		margin-left: 68%;
		margin-top: 77%;
		position: absolute;
		width: 120px
	}

	.dang {
		background-color: hsla(0, 0%, 100%, .0);
		color: #735B49;
		font-size: 28px;
		height: auto;
		margin-top: 5px;
		opacity: .5;
		text-align: center;
		width: 20%;
		margin-left: 10px;
	}

	.row_left {
		width: 45%;
		height: 40px;
		margin: 10px 5% 0 0%;
		align-items: center;
		display: flex;
		flex-direction: column;
		justify-content: center;
		border-radius: 10px;
	}

	.row_right {
		width: 45%;
		height: 40px;
		margin: 10px 0% 0 5%;
		align-items: center;
		display: flex;
		flex-direction: column;
		justify-content: center;
		border-radius: 10px;
	}

	.modalView {
		height: 50px;
		margin: 0 12px;
		border-radius: 10px;
		margin: 5px 15px auto;
		display: flex;
		flex-direction: row;
	}

	.row_one {
		width: 30%;
		height: 40px;
		margin: 10px 2.5% 0 0%;
		align-items: center;
		display: flex;
		flex-direction: column;
		justify-content: center;
		border-radius: 10px;
	}

	.row_two {
		width: 30%;
		height: 40px;
		margin: 10px 2.5% 0 2.5%;
		align-items: center;
		display: flex;
		flex-direction: column;
		justify-content: center;
		border-radius: 10px;
	}

	.row_three {
		width: 30%;
		height: 40px;
		margin: 10px 0% 0 2.5%;
		align-items: center;
		display: flex;
		flex-direction: column;
		justify-content: center;
		border-radius: 10px;
	}

	.colorPanel {
		background-color: hsla(0, 0%, 100%, .0);
		border-radius: 10px;
		margin: 15px 5% 10px 5%;
		height: auto;
		align-items: center;
		display: flex;
		flex-direction: column;
		justify-content: center;
	}

	.colorBlock {
		width: 60px;
		height: 10px;
		border-radius: 5px;
		margin-left: 10px;
		border-color: 'black';
		border-width: 1px;
	}

	.colorTitleDiv {
		display: flex;
		flex-direction: row;
		align-items: center;
	}

	.footer {
		position: fixed;
		bottom: 66px;
		width: 100%;
		z-index: 999;
		background-color: rgba(190, 152, 123, 1);
	}

	.main {
		padding-bottom: 66px;
		overflow-y: auto;
	}

	.on {
		width: 45px;
		height: 45px;
		position: absolute;
		margin-left: 44%;
		padding-top: 5px
	}

	.hud {
		position: fixed;
		background-color: rgba(0, 0, 0, 0.5);
		left: 0;
		right: 0;
		top: 0;
		bottom: 0;
		z-index: 998;
	}

	.popup-content {
		height: 248px;
	}

	.dialogTitle {
		font-size: 16px;
		text-align: center;
		height: 35px;
		padding-top: 10px;
	}
	
	.desText{
		color: #92735c;
		margin-right: 10px;
		flex: 1;
	}
</style>